﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace Baidu.AI.Helper
{
    public class BaiduAI
    {
        private readonly string access_token;
        public bool avaliable = false;
        public BaiduAI(string API_Key, string SecertKey)
        {
            string authHost = "https://aip.baidubce.com/oauth/2.0/token";
            HttpClient client = new();
            List<KeyValuePair<string, string>> paraList = new()
            {
                new KeyValuePair<string, string>("grant_type", "client_credentials"),
                new KeyValuePair<string, string>("client_id", API_Key),
                new KeyValuePair<string, string>("client_secret", SecertKey)
            };

            HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
            JObject result = JObject.Parse(response.Content.ReadAsStringAsync().Result);

            if (result["access_token"] != null)
            {
                access_token = ((string?)result["access_token"]) ?? "";
                avaliable = true;
            }
            else
            {
                throw (string?)result["error_description"] switch
                {
                    "unknown client id" => new Exception("API Key不正确"),
                    "Client authentication failed" => new Exception("Secret Key不正确"),
                    _ => new Exception("未知错误"),
                };
            }
        }

        public async Task<JObject> OcrInvoice(string FilePath)
        {
            JObject result;
            string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice?access_token=" + access_token;
            HttpClient httpClient = new();

            Dictionary<string, string> PostParam = new();

            string FileBase64 = GetFileBase64(FilePath);
            switch (Path.GetExtension(FilePath).ToLower())
            {
                case ".jpg":
                    PostParam.Add("image", FileBase64);
                    break;
                case ".png":
                    PostParam.Add("image", FileBase64);
                    break;
                case ".pdf":
                    PostParam.Add("pdf_file", FileBase64);
                    break;
                case ".ofd":
                    PostParam.Add("ofd_file", FileBase64);
                    break;
            }

            try
            {
                HttpContent PostContent = new FormUrlEncodedContent(PostParam);
                httpClient.Timeout = new TimeSpan(0, 0, 10);
                HttpResponseMessage response = await httpClient.PostAsync(host, PostContent);
                response.EnsureSuccessStatusCode();
                string httpClientRes = await response.Content.ReadAsStringAsync();
                result = JObject.Parse(httpClientRes);
                return result;
            }
            catch (Exception)
            {
                result = new JObject
                {
                    { "error_code", "1616001" }
                };
                return result;
            }
        }

        private static string GetFileBase64(string fileName)
        {
            FileStream filestream = new(fileName, FileMode.Open);
            byte[] arr = new byte[filestream.Length];
            filestream.Read(arr, 0, (int)filestream.Length);
            string baser64 = Convert.ToBase64String(arr);
            filestream.Close();
            return baser64;
        }
    }
}
